// pages/login/index.js
import { shareOptions } from '../../utils/access'
const api = require('../../config/api')
const request = require('../../utils/request')
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      url: options.url,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  /**
   * 微信用户快捷登录
   */
  async bindGetPhoneNumber(e) {
    const that = this
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      const isSuccess = await app.wxLogin(e?.detail)
      if (isSuccess) {
        wx.showLoading({
          title: '加载中',
          mask: false,
        })
        app.getPatientList()
        setTimeout(function () {
          // 用户界面登录根据情况跳转
          that.handleNavigate()
        }, 1000)
      }
    }
  },

  /**
   * 登录后跳转
   */
  async handleNavigate() {
    let { url } = this.data
    console.log('url',url);
    wx.hideLoading()
    let patientInfo = wx.getStorageSync('patientInfo')
    if (url !== 'user') {
      if (url === '/pages/sceneTrainDetail/index') {
        let collect = wx.getStorageSync('collect')
        if (collect === 1) {
          wx.navigateBack({
            delta: 1,
          })
        } else {
          if (!patientInfo) {
            app.globalData.createPatientEntrance = 5
            wx.navigateTo({
              url: '/pages/createPatient/select/select',
            })
          } else {
            this.handleJoinTraining()
          }
        }
      } else if (url === '/pages/index/index') {
        wx.switchTab({
          url: url,
        })
      } else if (url === '/pages/diary/index') {
        const { id } = patientInfo
        if (id) {
          wx.redirectTo({
            url: '/pages/diary/index',
          })
        } else {
          app.globalData.createPatientEntrance = 7
          wx.redirectTo({
            url: '/pages/createPatient/select/select',
          })
        }
      } else if (url === '/pages/activity/newUser/index') {
        app.backToPath('activity/newUser/index')
      } else if (url === '/pages/activity/inviteFriends/index') {
        app.backToPath('activity/inviteFriends/index')
      }else if (url === '/pages/activity/practiceAward/index') {
        let handleShare = wx.getStorageSync('handleShare')
        let activityId = wx.getStorageSync('activityId')

        console.log('登录过程------activityId---------',activityId)
        // 若点击的是分享按钮，则直接返回
        if(Number(handleShare) === 1){
          app.backToPath('activity/practiceAward/index')
        }else{
          // 没有孩子档案则去新建/绑定孩子档案
          if (!patientInfo) {
            app.globalData.createPatientEntrance = 9
            wx.navigateTo({
              url: '/pages/createPatient/select/select',
            })
          } else {
            let userId = wx.getStorageSync('userId')
            const res = await request.post(api.joinTrain,{activityTrainingId:activityId,userId})
            console.log('加入活动场景',res);
            if(res){
              // 返回活动页面
              app.backToPath('activity/practiceAward/index')
            }
          }
        }
      } else if(url==='/pages/activity/evaluationAnswer/index'){// 点击执行能力评估说明开始评估去登录
        console.log('patientInfo',patientInfo);
        if(patientInfo){
          let res = await request.get(api.getEvaluationResult)
          const {patientRecord} = res.data
          console.log('有评估结果',patientRecord);
          // 有评估结果---进入评估结果页
          if(patientRecord){
            wx.redirectTo({
              url: '/pages/activity/evaluationResult/index',
            })
          }else{
            // 没评估结果---进入评估说明页
            wx.redirectTo({
              url: '/pages/activity/evaluationAnswer/index?isChild=1',
            })
          }
        }else{
          app.globalData.createPatientEntrance = 10
          wx.navigateTo({
            url: '/pages/createPatient/select/select',
          })
        }
      }else {
        wx.navigateTo({
          url: url,
        })
      }
    } else {
      wx.navigateBack({
        delta: 1,
      })
    }
  },
  /**
   * 加入训练
   */
  async handleJoinTraining() {
    let trainingId = wx.getStorageSync('trainingId') || wx.getStorageSync('activityTrainingId')
    let patientInfo = wx.getStorageSync('patientInfo')
    // 新建孩子档案后直接加入训练
    const res = await request.post(
      api.joinTraining,
      {
        bindBeforeId: trainingId,
        patientId: patientInfo.id,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      let { startDate, trainingName } = res.data.trainingTemplateInfo
      let { detailId, trainingType, questionnaireId } =
        res.data.trainingDetailInfo
      let trainingId1 = res.data.trainingDetailInfo.trainingId
      let { isNeedEject } = res.data
      wx.redirectTo({
        url: `/pages/practiceJoin/index?startDate=${startDate}&trainingId=${trainingId1}&trainingName=${trainingName}&detailId=${detailId}&trainingType=${trainingType}&questionnaireId=${questionnaireId}&isNeedEject=${isNeedEject}`,
      })
    } else {
      wx.navigateBack({
        delta: 1,
      })
      setTimeout(() => {
        wx.showToast({
          title: res.msg ? res.msg : '加入失败',
          icon: 'none',
        })
      }, 1000)
    }
  },

  /**
   * 手机号登录
   */
  handlePhoneLogin() {
    wx.navigateTo({
      url: '/pages/login-phone/login-phone',
    })
  },
  // 用户点击右上角分享
  onShareAppMessage() {
    return shareOptions()
  },
})
